home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1993 July / InfoMagic USENET CD-ROM July 1993.ISO / sources / unix / volume25 / zip / part07 < prev    next >
Encoding:
Text File  |  1992-03-01  |  47.3 KB  |  1,450 lines

  1. Newsgroups: comp.sources.unix
  2. From: madler@cco.caltech.edu (Mark Adler)
  3. Subject: v25i148: zip - file compression/archive tool, Part07/07
  4. Sender: unix-sources-moderator@pa.dec.com
  5. Approved: vixie@pa.dec.com
  6.  
  7. Submitted-By: madler@cco.caltech.edu (Mark Adler)
  8. Posting-Number: Volume 25, Issue 148
  9. Archive-Name: zip/part07
  10.  
  11. #! /bin/sh
  12. # This is a shell archive.  Remove anything before this line, then unpack
  13. # it by saving it into a file and typing "sh file".  To overwrite existing
  14. # files, type "sh file -c".  You can also feed this as standard input via
  15. # unshar, or by typing "sh <file", e.g..  If this archive is complete, you
  16. # will see the following message at the end:
  17. #        "End of archive 7 (of 7)."
  18. # Contents:  im_ctree.c
  19. # Wrapped by vixie@cognition.pa.dec.com on Sun Mar  1 18:57:39 1992
  20. PATH=/bin:/usr/bin:/usr/ucb ; export PATH
  21. if test -f 'im_ctree.c' -a "${1}" != "-c" ; then 
  22.   echo shar: Will not clobber existing file \"'im_ctree.c'\"
  23. else
  24. echo shar: Extracting \"'im_ctree.c'\" \(45523 characters\)
  25. sed "s/^X//" >'im_ctree.c' <<'END_OF_FILE'
  26. X/*
  27. X
  28. X Copyright (C) 1990,1991 Mark Adler, Richard B. Wales, and Jean-loup Gailly.
  29. X Permission is granted to any individual or institution to use, copy, or
  30. X redistribute this software so long as all of the original files are included
  31. X unmodified, that it is not sold for profit, and that this copyright notice
  32. X is retained.
  33. X
  34. X*/
  35. X
  36. X/*
  37. X *  im_ctree.c by Richard B. Wales.
  38. X *
  39. X *  Includes modifications by Jean-Loup Gailly.
  40. X *
  41. X *  PURPOSE
  42. X *
  43. X *      Encode various sets of source values using variable-length
  44. X *      binary code trees.
  45. X *
  46. X *  DISCUSSION
  47. X *
  48. X *      The PKZIP "implosion" process uses several variable-depth binary
  49. X *      code trees, similar to Huffman trees.  The more common source
  50. X *      values are represented by shorter bit sequences.
  51. X *
  52. X *      Each code tree is stored in the ZIP file in a compressed form
  53. X *      that is essentially a run-length-encoded list of the lengths of
  54. X *      all the code strings (in ascending order by source values).
  55. X *      The actual code strings are reconstructed from the lengths in
  56. X *      the UNZIP process, as described in the "application note"
  57. X *      (APPNOTE.TXT) distributed as part of PKWARE's PKZIP program.
  58. X *
  59. X *      Because of the way a code tree is stored in the ZIP file, the
  60. X *      codes must conform to the following restrictions:
  61. X *
  62. X *      (1) No code string may ever exceed 16 bits in length.
  63. X *
  64. X *      (2) If all code strings are extended to 16 bits by padding on
  65. X *          the right (low-order end) with zeros, and then treated as
  66. X *          unsigned 16-bit integers, then:
  67. X *
  68. X *          (a) The arithmetically higher 16-bit values must correspond
  69. X *              to the shorter code strings.
  70. X *
  71. X *          (b) If two source values map into code strings of the same
  72. X *              length, the higher code string must correspond to the
  73. X *              lower source value (where source values are treated as
  74. X *              unsigned).
  75. X *
  76. X *      Further, shortcuts taken by PKUNZIP 1.10 in the way it decodes
  77. X *      the compressed data via the trees impose the following extra
  78. X *      limitations:
  79. X *
  80. X *      (3) No code string in the "distance" tree can be longer than 8
  81. X *          bits.
  82. X *
  83. X *      (4) The maximum length of any code string is limited by the
  84. X *          number of initial zero bits, as follows:
  85. X *
  86. X *          (a) 0-3 leading zeros:  maximum length is 8.
  87. X *
  88. X *          (b) 4-5 leading zeros:  maximum length is 12.
  89. X *
  90. X *          (c) 6-7 leading zeros:  maximum length is 14.
  91. X *
  92. X *      (5) In the "literal" tree, the code string corresponding to the
  93. X *          source value 255 must be at least 10 bits in length, regard-
  94. X *          less of the frequency of the value 255 in the file.
  95. X *
  96. X *      PKWARE calls the code trees "Shannon-Fano trees".  (Shannon-Fano
  97. X *      coding was a predecessor to the better-known Huffman coding
  98. X *      technique; see the references below.)  Although it appears that
  99. X *      the Shannon-Fano (top-down partitioning) algorithm is in fact
  100. X *      used by PKZIP in the process of creating the code trees, the
  101. X *      resulting trees are not in fact "pure" Shannon-Fano, because of
  102. X *      the extra processing required in order to meet the restrictions
  103. X *      described above.
  104. X *
  105. X *  REFERENCES
  106. X *
  107. X *      Lynch, Thomas J.
  108. X *          Data Compression:  Techniques and Applications, pp. 53-55.
  109. X *          Lifetime Learning Publications, 1985.  ISBN 0-534-03418-7.
  110. X *
  111. X *      Storer, James A.
  112. X *          Data Compression:  Methods and Theory, pp. 49-50.
  113. X *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
  114. X *
  115. X *  INTERFACE
  116. X *
  117. X *      ImpErr ct_init (void)
  118. X *          Initialize the code tree routines.  This routine must be
  119. X *          called before any other code tree routines may be called.
  120. X *
  121. X *      ImpErr ct_tally (MATCH *ma)
  122. X *          Tally a "string match" data set.  The tally results will be
  123. X *          used to determine how large the imploded result will be.
  124. X *
  125. X *      ImpErr ct_mktrees (FDATA *fd)
  126. X *          Construct all code trees, and then determine how big the
  127. X *          imploded file will be under both "literal tree" and "no
  128. X *          literal tree" conditions.  Choose the best option.
  129. X *
  130. X *      ImpErr ct_wrtrees (FILE *outfp)
  131. X *          Output the code trees to the ZIP file.
  132. X *
  133. X *      ImpErr ct_wrdata (FILE *outfp)
  134. X *          Output the file data to the ZIP file.
  135. X *
  136. X *      ImpErr ct_windup (void)
  137. X *          Deallocate all code trees.
  138. X */
  139. X
  140. X
  141. X#ifdef DEBUG
  142. X#   define VALIDATE
  143. X#endif /* DEBUG */
  144. X
  145. X#include "implode.h"
  146. X
  147. X
  148. X/***********************************************************************
  149. X *
  150. X * Local data used by the "code tree" routines.
  151. X */
  152. X
  153. X
  154. X/* Data structure describing a single value and its code string. */
  155. typedef
  156. struct  ct_data
  157. X    {   UL_INT  ct_freq;                /* frequency count */
  158. X        US_INT  ct_code;                /* bit string */
  159. X        U_CHAR  ct_len;                 /* length of bit string */
  160. X        U_CHAR  ct_val;                 /* source value */
  161. X    }
  162. X    TRDATA;
  163. X
  164. X
  165. X/*
  166. X * Data structure for re-sorting source values by bit string length;
  167. X * used during tree generation.
  168. X */
  169. typedef
  170. struct  ct_resort
  171. X    {   U_CHAR  ct_rlen;                /* length of bit string */
  172. X        U_CHAR  ct_rval;                /* source value */
  173. X#ifdef VMS
  174. X        US_INT  dummy;                  /* because of bug in qsort() */
  175. X#endif /* VMS */
  176. X    }
  177. X    RESORT;
  178. X
  179. X
  180. X/* Header for a code tree. */
  181. typedef
  182. struct  ct_desc
  183. X    {   TRDATA *ct_array;               /* array of TRDATA */
  184. X        int     ct_size;                /* # of entries in tree */
  185. X    }
  186. X    TRDESC;
  187. X
  188. X
  189. X/*
  190. X * Currently active code trees.
  191. X * We allow for five trees (one literal tree, two length trees, and
  192. X * two distance trees) so that we can evaluate the total compression
  193. X * with or without the use of the literal tree.  Remember that the
  194. X * minimum matching distance depends on whether or not a literal tree
  195. X * is used; hence, the "length" and "distance" trees will differ.
  196. X */
  197. X#define MAXTREES        5               /* max # of trees at once */
  198. local   TRDESC  ct_table[MAXTREES];
  199. X
  200. X
  201. X/* Macro to validate a code tree handle. */
  202. X#define VALID_HANDLE(x) \
  203. X        ((x) >= 0 && (x) < MAXTREES && ct_table[x].ct_array != NULL)
  204. X
  205. X
  206. X/*
  207. X * Assorted frequency counts.
  208. X * The "Minimum Match Length" (MML) is 2 if a "literal character" code
  209. X * tree is not used, or 3 if a "literal character" tree is used.  Thus,
  210. X * we need to keep two sets of "length" and "distance" frequency counts.
  211. X * Also, 2-character matches need to be counted separately; depending
  212. X * on whether a "literal character" tree is used or not, these will be
  213. X * processed either as literal characters or as distance/length pairs.
  214. X */
  215. X
  216. X/* Total number of source values from Pass One. */
  217. local   long    ct_litc_num;            /* total # literal chars */
  218. local   long    ct_lit2_num;            /* total # of 2-char matches */
  219. local   long    ct_strg_num;            /* total # of string matches */
  220. X
  221. X/* Source value frequencies for the five trees. */
  222. local   long    ct_litc_freq[256];      /* literal character freqs */
  223. local   long    ct_len2_freq[64];       /* length freqs (MML=2) */
  224. local   long    ct_len3_freq[64];       /* length freqs (MML=3) */
  225. local   long    ct_dst2_freq[64];       /* distance freqs (MML=2) */
  226. local   long    ct_dst3_freq[64];       /* distance freqs (MML=3) */
  227. X
  228. X/* Number of bits saved by using each of the trees. */
  229. local   long    ct_litc_saved;          /* literal tree */
  230. local   long    ct_len2_saved;          /* length tree (MML=2) */
  231. local   long    ct_len3_saved;          /* length tree (MML=3) */
  232. local   long    ct_dst2_saved;          /* distance tree (MML=2) */
  233. local   long    ct_dst3_saved;          /* distance tree (MML=3) */
  234. X
  235. X/* Handles for the code trees to be used. */
  236. local   int     ct_litc_tree;           /* temp literal tree */
  237. local   int     ct_len2_tree;           /* temp length tree (MML=2) */
  238. local   int     ct_len3_tree;           /* temp length tree (MML=3) */
  239. local   int     ct_dst2_tree;           /* temp distance tree (MML=2) */
  240. local   int     ct_dst3_tree;           /* temp distance tree (MML=3) */
  241. local   int     lit_tree;               /* literal tree (-1 if none) */
  242. local   int     len_tree;               /* length tree */
  243. local   int     dst_tree;               /* distance tree */
  244. X
  245. X
  246. X/***********************************************************************
  247. X *
  248. X * Local (static) routines in this file.
  249. X */
  250. X
  251. local ImpErr ct_alloc
  252. X        OF ((int size, int *handle));
  253. X
  254. local ImpErr ct_free
  255. X        OF ((int handle));
  256. X
  257. local ImpErr ct_loadf
  258. X        OF ((int handle, long *freq));
  259. X
  260. local ImpErr ct_ziprep
  261. X        OF ((int handle, U_CHAR **result));
  262. X
  263. local ImpErr ct_gencodes
  264. X        OF ((int handle, int minbits, int maxbits, long *saved));
  265. X
  266. local ImpErr ct_split
  267. X        OF ((TRDATA *part, int size, long freq,
  268. X             int prefix, int preflen, int minbits, int maxbits));
  269. X
  270. local int ct_fsort
  271. X        OF ((TRDATA *tr1, TRDATA *tr2));
  272. X
  273. local int ct_rsort
  274. X        OF ((RESORT *cr1, RESORT *cr2));
  275. X
  276. X
  277. X/***********************************************************************
  278. X *
  279. X * Allocate a code tree.
  280. X */
  281. X
  282. local
  283. ImpErr
  284. ct_alloc (size, handle)
  285. X    int size;
  286. X    int *handle;
  287. X{   register TRDATA *ct;
  288. X    int n;
  289. X
  290. X#ifdef VALIDATE
  291. X    /* Validate the arguments. */
  292. X    if (size < 2 || size > 256) goto badarg;
  293. X    if (handle == NULL)         goto badarg;
  294. X#endif /* VALIDATE */
  295. X
  296. X    /* Allocate an available code tree handle. */
  297. X    for (n = 0;
  298. X         n < MAXTREES && ct_table[n].ct_array != NULL;
  299. X         n++) ;
  300. X    if (n >= MAXTREES) return IM_NOCTBLS;
  301. X    *handle = n;
  302. X    ct_table[n].ct_size  = size;
  303. X
  304. X    /* Allocate space for the code tree. */
  305. X    ct = (TRDATA *) malloc ((unsigned) (size * sizeof (TRDATA)));
  306. X    if (ct == NULL) return IM_NOMEM;
  307. X    ct_table[n].ct_array = ct;
  308. X
  309. X    /* Initialize the code tree. */
  310. X    for (n = 0; n < size; n++, ct++)
  311. X    {   ct->ct_freq = 0;
  312. X        ct->ct_code = 0;
  313. X        ct->ct_val  = (U_CHAR)n;
  314. X        ct->ct_len  = 0;
  315. X    }
  316. X
  317. X    /* That's all. */
  318. X    return IM_OK;
  319. X
  320. X#ifdef VALIDATE
  321. badarg:
  322. X    fprintf (stderr, "\nError in ct_alloc: bad argument(s)");
  323. X    return IM_BADARG;
  324. X#endif /* VALIDATE */
  325. X}
  326. X
  327. X
  328. X/***********************************************************************
  329. X *
  330. X * Free a code tree.
  331. X */
  332. X
  333. local
  334. ImpErr
  335. ct_free (handle)
  336. X    int handle;
  337. X{
  338. X#ifdef VALIDATE
  339. X    /* Validate the argument. */
  340. X    if (!VALID_HANDLE (handle)) goto badarg;
  341. X#endif /* VALIDATE */
  342. X
  343. X    /* Free the code tree. */
  344. X    free ((char *) ct_table[handle].ct_array);
  345. X    ct_table[handle].ct_array = NULL;
  346. X    ct_table[handle].ct_size  = 0;
  347. X
  348. X    /* That's all. */
  349. X    return IM_OK;
  350. X
  351. X#ifdef VALIDATE
  352. badarg:
  353. X    fprintf (stderr, "\nError in ct_free: bad argument(s)");
  354. X    return IM_BADARG;
  355. X#endif /* VALIDATE */
  356. X}
  357. X
  358. X
  359. X/***********************************************************************
  360. X *
  361. X * Update a code tree with frequency data.
  362. X *
  363. X * In order to allow for the later addition of "adaptive" coding,
  364. X * the new frequencies are added to the existing data.
  365. X */
  366. X
  367. local
  368. ImpErr
  369. ct_loadf (handle, freq)
  370. X    int   handle;
  371. X    long *freq;
  372. X{   register long *f;
  373. X    register TRDATA *ct;
  374. X    int n;
  375. X
  376. X#ifdef VALIDATE
  377. X    /* Validate the arguments. */
  378. X    if (!VALID_HANDLE (handle)) goto badarg;
  379. X#endif /* VALIDATE */
  380. X
  381. X    /* Add in the frequencies. */
  382. X    for (f = freq,
  383. X             ct = ct_table[handle].ct_array,
  384. X             n = ct_table[handle].ct_size;
  385. X         n > 0;
  386. X         f++, ct++, n--)
  387. X        ct->ct_freq += *f;
  388. X
  389. X    /* That's all. */
  390. X    return IM_OK;
  391. X
  392. X#ifdef VALIDATE
  393. badarg:
  394. X    fprintf (stderr, "\nError in ct_loadf: bad argument(s)");
  395. X    return IM_BADARG;
  396. X#endif /* VALIDATE */
  397. X}
  398. X
  399. X
  400. X/***********************************************************************
  401. X *
  402. X * Generate the ZIP-file representation for a code tree.
  403. X *
  404. X * The returned "result" value points to static data which will be
  405. X * overwritten on the next call to "ct_ziprep".
  406. X *
  407. X * The length of the result string is implicit in the first byte of
  408. X * the value, as specified in the PKZIP applications note.
  409. X */
  410. X
  411. X#ifdef IMPDEBUG
  412. char *treename;
  413. X#endif /* IMPDEBUG */
  414. X
  415. local
  416. ImpErr
  417. ct_ziprep (handle, result)
  418. X    int      handle;
  419. X    U_CHAR **result;
  420. X{   static U_CHAR buffer[257];          /* result info */
  421. X    register U_CHAR *c;
  422. X    register TRDATA *ct;
  423. X    int s, n, l;
  424. X
  425. X#ifdef VALIDATE
  426. X    /* Validate the arguments. */
  427. X    if (!VALID_HANDLE (handle)) goto badarg;
  428. X    if (result == NULL)         goto badarg;
  429. X#endif /* VALIDATE */
  430. X
  431. X#ifdef  IMPDEBUG
  432. X    if (treename != NULL && treename[0] != 0)
  433. X    {   /* Print the code tree info. */
  434. X        fprintf (stderr, "\n%s tree:\n  value      len   string\n",
  435. X                 treename);
  436. X        for (ct = ct_table[handle].ct_array,
  437. X                  s = ct_table[handle].ct_size,
  438. X                  n = 0;
  439. X             s > 0;
  440. X             ct++, n++, s--)
  441. X            fprintf (stderr, "  %3d (%02x)    %2d    %04x (rev %04x)\n",
  442. X                     n, n, ct->ct_len,
  443. X                     bi_reverse(ct->ct_code << (16 - ct->ct_len),
  444. X                                ct->ct_len) << (16 - ct->ct_len),
  445. X                     ct->ct_code);
  446. X    }
  447. X#endif  /* IMPDEBUG */
  448. X
  449. X    /* Generate the returned value. */
  450. X    for (c = buffer+1,
  451. X             ct = ct_table[handle].ct_array,
  452. X             s = ct_table[handle].ct_size,
  453. X             n = 0,
  454. X             l = ct->ct_len;
  455. X         s > 0;
  456. X         ct++, s--)
  457. X    {   if (l < 1 || l > 16)
  458. X        {   fprintf (stderr, "\nError in ct_ziprep: bad code length");
  459. X            return IM_LOGICERR;
  460. X        }
  461. X        if (n >= 16 || (int)ct->ct_len != l)
  462. X        {   *c++ = (U_CHAR)((((n-1) << 4) & 0xf0) | ((l-1) & 0x0f));
  463. X            n = 1; l = ct->ct_len;
  464. X        }
  465. X        else n++;
  466. X    }
  467. X    if (n > 0)
  468. X        *c++ = (U_CHAR)((((n-1) << 4) & 0xf0) | ((l-1) & 0x0f));
  469. X    buffer[0] = (U_CHAR)((c - buffer) - 2);
  470. X
  471. X    /* That's all. */
  472. X    *result = buffer;
  473. X    return IM_OK;
  474. X
  475. X#ifdef VALIDATE
  476. badarg:
  477. X    fprintf (stderr, "\nError in ct_ziprep: bad argument(s)");
  478. X    return IM_BADARG;
  479. X#endif /* VALIDATE */
  480. X}
  481. X
  482. X
  483. X/***********************************************************************
  484. X *
  485. X * Look up the code string for a given value.
  486. X */
  487. X
  488. X#define ct_lookup(handle, value, string, length) \
  489. X{   register TRDATA *ct; \
  490. X    ct = ct_table[handle].ct_array + (value); \
  491. X    string = ct->ct_code; \
  492. X    length = ct->ct_len; \
  493. X}
  494. X
  495. X
  496. X/***********************************************************************
  497. X *
  498. X * Generate the codes for a code tree.  If old codes already exist for
  499. X * the tree, they are discarded, and a new set of codes is generated
  500. X * from scratch.
  501. X * IN assertion: ma_buf is already allocated and can be overwritten.
  502. X */
  503. X
  504. local
  505. ImpErr
  506. ct_gencodes (handle, minbits, maxbits, saved)
  507. X    int   handle;                       /* which tree */
  508. X    int   minbits;                      /* min code string bit length */
  509. X    int   maxbits;                      /* max code string bit length */
  510. X    long *saved;                        /* how many bits saved */
  511. X{   register TRDATA *ct;
  512. X    TRDATA *ct2;
  513. X    register int n;
  514. X    UL_INT f;
  515. X    register RESORT *cr;
  516. X    int code, srclen;
  517. X    long totalfreq, totalbits;
  518. X    ImpErr retcode;
  519. X    RESORT rbuf[256];
  520. X    int size; /* alias for ct_table[handle].ct_size */
  521. X    int z;    /* index of zero frequency element */
  522. X    int nz;   /* index of non zero frequency element */
  523. X
  524. X#ifdef VALIDATE
  525. X    /* Validate the arguments. */
  526. X    if (!VALID_HANDLE (handle)) goto badarg;
  527. X    if (minbits < 1)            goto badarg;
  528. X    if (maxbits > 16)           goto badarg;
  529. X    if (maxbits < minbits)      goto badarg;
  530. X    if (saved == NULL)          goto badarg;
  531. X#endif /* VALIDATE */
  532. X    size = ct_table[handle].ct_size;
  533. X
  534. X    /*
  535. X     * Start by sorting the data by frequency.  The source values with
  536. X     * higher frequency need to get the shorter Shannon-Fano codes.
  537. X     * First exclude the elements with zero frequency, to speed up the sort.
  538. X     * This optimization is very important for small files, otherwise the sort
  539. X     * takes most of the implode time.
  540. X     *    Also determine the total of all frequencies.  This will be needed in
  541. X     * order to partition the source values in the Shannon-Fano bit
  542. X     * string computation. Finally clear the "code" (bit string) and "len"
  543. X     * (bit string length) fields in the code tree array.
  544. X     */
  545. X    totalfreq = 0;
  546. X    ct = ct_table[handle].ct_array;
  547. X    /* Copy ct into a tempo */
  548. X    ct2 = (TRDATA*) ma_buf;
  549. X    memcpy((char*)ct2, (char*)ct, size * sizeof(TRDATA));
  550. X    for (nz = 0, z = n = size-1; n >= 0; n--) {
  551. X        int m;
  552. X        if (ct2[n].ct_freq != 0L) {
  553. X            m = nz++;
  554. X            totalfreq += (ct[m].ct_freq = ct2[n].ct_freq);
  555. X        } else {
  556. X            m = z--;
  557. X            ct[m].ct_freq = 0L;
  558. X        }
  559. X        ct[m].ct_code = 0;
  560. X        ct[m].ct_len = 0;
  561. X        ct[m].ct_val = (U_CHAR)n; /* ct2[n].ct_val */
  562. X    }
  563. X    qsort ((char *) (ct_table[handle].ct_array), nz,
  564. X           sizeof (TRDATA), (int (*)())ct_fsort);
  565. X
  566. X    /*
  567. X     * Generate the bit strings via a Shannon-Fano (top-down) algorithm.
  568. X     */
  569. X    retcode =
  570. X        ct_split (ct_table[handle].ct_array,    /* partition start */
  571. X                  size,                         /* partition size */
  572. X                  totalfreq,                    /* total frequency */
  573. X                  0,                            /* code string prefix */
  574. X                  0,                            /* # bits in prefix */
  575. X                  minbits,                      /* minimum tree depth */
  576. X                  maxbits);                     /* maximum tree depth */
  577. X    if (retcode != IM_OK) return retcode;
  578. X
  579. X    /*
  580. X     * The source value 255 needs to be assigned a bit string with a
  581. X     * length of at least 10, in order to accommodate shortcuts in
  582. X     * PKUNZIP's decoding algorithm.  If no bit string in the tree is
  583. X     * of length 10, we assign 255 to the longest string and hope for
  584. X     * the best.
  585. X     */
  586. X    n = size;
  587. X    if (n == 256)
  588. X    {   for (ct = ct_table[handle].ct_array;
  589. X             n > 0 && ct->ct_val != 255;
  590. X             n--, ct++) ;
  591. X        if (n == 0)
  592. X        {   fprintf (stderr, "\nError in ct_gencodes: no value 255");
  593. X            return IM_LOGICERR;
  594. X        }
  595. X        if (ct->ct_len < 10)
  596. X        {   ct2 = ct;
  597. X            while (n > 0 && ct->ct_len < 10) n--, ct++;
  598. X            if (n == 0) ct--;   /* no len>=10 in tree; use longest */
  599. X            n = ct->ct_val;
  600. X                ct->ct_val = ct2->ct_val;
  601. X                ct2->ct_val = (U_CHAR)n;
  602. X            f = ct->ct_freq;
  603. X                ct->ct_freq = ct2->ct_freq;
  604. X                ct2->ct_freq = f;
  605. X    }   }
  606. X
  607. X    /*
  608. X     * The source values need to be re-sorted so that all source values
  609. X     * with code strings of the same length will be in ascending order.
  610. X     * This is because of the compression scheme used to represent the
  611. X     * tree in the ZIP file.
  612. X     */
  613. X    for (n = size,
  614. X             ct = ct_table[handle].ct_array,
  615. X             cr = rbuf;
  616. X         n > 0;
  617. X         n--, ct++, cr++)
  618. X    {   cr->ct_rlen = ct->ct_len;
  619. X        cr->ct_rval = ct->ct_val;
  620. X    }
  621. X    n = size;
  622. X    qsort ((char *) rbuf, n, sizeof (RESORT), (int (*)())ct_rsort);
  623. X    for (ct = ct_table[handle].ct_array,
  624. X             cr = rbuf;
  625. X         n > 0;
  626. X         n--, ct++, cr++)
  627. X        ct->ct_val = cr->ct_rval;
  628. X
  629. X#ifdef DUMP_TREE
  630. X    printf ("Finished tree:\n");
  631. X    for (n = size,
  632. X             ct = ct_table[handle].ct_array;
  633. X         n > 0;
  634. X         n--, ct++)
  635. X        printf ("  %3d (0x%02x)  l %2d  c 0x%04x f %ld\n",
  636. X                ct->ct_val, ct->ct_val, ct->ct_len, ct->ct_code, ct->ct_freq);
  637. X    putchar ('\n');
  638. X#endif /* DUMP_TREE */
  639. X
  640. X    /*
  641. X     * Finally, sort the tree back in ascending order by source value
  642. X     * -- which is the order expected by other portions of the program.
  643. X     */
  644. X    ct = ct_table[handle].ct_array;
  645. X    /* Copy ct into a tempo */
  646. X    ct2 = (TRDATA*)ma_buf;
  647. X    memcpy((char*)ct2, (char*)ct, size * sizeof(TRDATA));
  648. X    for (n = size-1; n >= 0; n--) {
  649. X        U_CHAR v = ct2[n].ct_val;
  650. X        ct[v].ct_freq = ct2[n].ct_freq;
  651. X        ct[v].ct_code = ct2[n].ct_code;
  652. X        ct[v].ct_len = ct2[n].ct_len;
  653. X        ct[v].ct_val = v;
  654. X    }
  655. X
  656. X    /*
  657. X     * Determine how many bits will be saved if all the source data is
  658. X     * encoded using this new set of code strings, as opposed to being
  659. X     * represented directly in unencoded form.
  660. X     */
  661. X    /* # of bits needed for unencoded source values */
  662. X    n = ct_table[handle].ct_size;
  663. X    for (code = 1, srclen = 0; code < n; code <<= 1, srclen++) ;
  664. X    /* # of bits used if all source values encoded via this tree */
  665. X    for (ct = ct_table[handle].ct_array,
  666. X             totalbits = 0;
  667. X         n > 0;
  668. X         n--, ct++)
  669. X        totalbits += ct->ct_freq * ct->ct_len;
  670. X    /* # bits saved by using the tree */
  671. X    *saved = (totalfreq * srclen) - totalbits;
  672. X
  673. X    /* That's all. */
  674. X    return IM_OK;
  675. X
  676. X#ifdef VALIDATE
  677. badarg:
  678. X    fprintf (stderr, "\nError in ct_gencodes: bad argument(s)");
  679. X    return IM_BADARG;
  680. X#endif /* VALIDATE */
  681. X}
  682. X
  683. X
  684. X/***********************************************************************
  685. X *
  686. X * Split a portion of a code tree into two pieces of approximately equal
  687. X * total frequency.  This routine calls itself recursively in order to
  688. X * generate the bit strings for the entire code tree.
  689. X */
  690. X
  691. local
  692. ImpErr
  693. ct_split (part, size, freq, prefix, preflen, minbits, maxbits)
  694. X    TRDATA *part;               /* start of partition */
  695. X    int     size;               /* # elements in partition */
  696. X    long    freq;               /* sum of frequencies in partition */
  697. X    int     prefix;             /* initial code bits for partition */
  698. X    int     preflen;            /* # bits in prefix */
  699. X    int     minbits;            /* minimum permissible bit length */
  700. X    int     maxbits;            /* maximum permissible bit length */
  701. X{   register TRDATA *ct;
  702. X    int topmaxbits, botmaxbits, localminbits;
  703. X    U_INT topmaxvals, botmaxvals;
  704. X    int topsize, botsize;
  705. X    long topfreq, botfreq, halffreq, onefreq;
  706. X    int n, m, leadzeros;
  707. X    int maxshort, minlong;
  708. X    ImpErr retcode;
  709. X    static maxarray[17] =
  710. X        { 8,8,8,8,12,12,14,14,16,16,16,16,16,16,16,16,16 };
  711. X
  712. X#ifdef VALIDATE
  713. X    if (part == NULL)           goto badarg;
  714. X    if (size < 1)               goto badarg;
  715. X    if (freq < 0)               goto badarg;
  716. X    if (preflen < 0)            goto badarg;
  717. X    if (preflen > maxbits)      goto badarg;
  718. X    if (minbits < preflen)      goto badarg;
  719. X    if (maxbits > 16)           goto badarg;
  720. X    if (maxbits < minbits)      goto badarg;
  721. X    /*
  722. X    putc ('\n', stderr);
  723. X    for (n = preflen; n > 0; n--) fprintf (stderr, "   ");
  724. X    fprintf (stderr, "ct_split (sz=%d, pr=%04x[%d], min=%d, max=%d)",
  725. X             size, prefix, preflen, minbits, maxbits);
  726. X    */
  727. X#endif /* VALIDATE */
  728. X
  729. X    /*
  730. X     * If there's only one element in this partition, we simply take
  731. X     * the "prefix" value as the code string for the single element.
  732. X     * We reverse the bits of the prefix for more efficient output.
  733. X     */
  734. X    if (size == 1)
  735. X    {   part->ct_code = bi_reverse(prefix, preflen);
  736. X        part->ct_len  = (U_CHAR)preflen;
  737. X        return IM_OK;
  738. X    }
  739. X
  740. X    /*
  741. X     * This partition will be divided into two parts.  The "top" part
  742. X     * will have a "1" bit appended to its "prefix" bit string; the
  743. X     * "bottom" part will have a "0" bit appended to its "prefix".
  744. X     *
  745. X     * We need to determine the maximum number of source values which
  746. X     * may be assigned to the two partitions.  The first issue to con-
  747. X     * sider is that PKUNZIP 1.10's tree-decoding shortcuts require a
  748. X     * certain number of leading "0" bits in each code string, depending
  749. X     * on its length.  Code strings of 9-12 bits must have at least 4
  750. X     * leading zeros; strings of 13 or 14 bits, at least 6 leading
  751. X     * zeros; and strings of 15 or 16 bits, at least 8 leading zeros.
  752. X     *
  753. X     * If the "prefix" is zero, the above limitation is used to restrict
  754. X     * the maximum size of the top half of the partition.  The bottom
  755. X     * half does not need to be restricted in this way, since it can be
  756. X     * extended as far as needed along the path where the "prefix" grows
  757. X     * in length but remains all zero.
  758. X     */
  759. X    botmaxbits = maxbits;
  760. X    if (prefix != 0) topmaxbits = maxbits;
  761. X    else
  762. X    {   for (n = 0, leadzeros = 0x8000;
  763. X             n < preflen && (prefix & leadzeros) == 0;
  764. X             n++, leadzeros >>= 1) ;
  765. X        topmaxbits = maxarray[n];
  766. X        if (topmaxbits > maxbits) topmaxbits = maxbits;
  767. X    }
  768. X    if (topmaxbits < minbits)
  769. X    {   fprintf (stderr, "\nError in ct_split: ");
  770. X        fprintf (stderr, "topmaxbits(%d) < minbits(%d)",
  771. X                 topmaxbits, minbits);
  772. X        goto oops;
  773. X    }
  774. X    if (botmaxbits < minbits)
  775. X    {   fprintf (stderr, "\nError in ct_split: ");
  776. X        fprintf (stderr, "botmaxbits(%d) < minbits(%d)",
  777. X                 botmaxbits, minbits);
  778. X        goto oops;
  779. X    }
  780. X    topmaxvals = 1 << (topmaxbits - preflen - 1);
  781. X    n = size >> 1; if (topmaxvals > n) topmaxvals = n;
  782. X    botmaxvals = 1 << (botmaxbits - preflen - 1);
  783. X    n = size - 1;  if (botmaxvals > n) botmaxvals = n;
  784. X    if (topmaxvals + botmaxvals < size)
  785. X    {   fprintf (stderr, "\nError in ct_split: ");
  786. X        fprintf (stderr, "topmaxvals(%d) + botmaxvals(%d) ",
  787. X                 topmaxvals, botmaxvals);
  788. X        fprintf (stderr, "< size(%d)", size);
  789. X        goto oops;
  790. X    }
  791. X
  792. X    /*
  793. X     * We now split the current partition into two halves of as close
  794. X     * to equal frequency as possible.  If the total of all frequencies
  795. X     * in the partition is zero, split into two halves of equal size.
  796. X     */
  797. X    if (freq == 0)
  798. X    {   topsize = size >> 1;
  799. X        ct = part + topsize;
  800. X        topfreq = 0;
  801. X    }
  802. X    else
  803. X    {   halffreq = freq >> 1;           /* half the total frequency */
  804. X        m = size >> 1;                  /* half the total elements, */
  805. X                                        /*    rounded down          */
  806. X        for (topsize = 0, topfreq = 0, ct = part;
  807. X             topsize < m && topfreq <= halffreq
  808. X                 && (onefreq = ct->ct_freq) > 0;
  809. X             topsize++, ct++)
  810. X            topfreq += onefreq;
  811. X        if (topsize >= 2)
  812. X        {   /*
  813. X             * If moving one element from the top to the bottom parti-
  814. X             * tion would make the two more closely equal in frequency,
  815. X             * do it.
  816. X             */
  817. X            onefreq = (ct-1)->ct_freq;
  818. X            if ((topfreq - halffreq) > (halffreq - (topfreq - onefreq)))
  819. X                ct--, topsize--, topfreq -= onefreq;
  820. X    }   }
  821. X    botsize = size - topsize;
  822. X    botfreq = freq - topfreq;
  823. X    /* "ct" points to first element in bottom half */
  824. X
  825. X    /*
  826. X     * The above first-cut attempt to split the partition may not work
  827. X     * for one of two reasons.  First, one or the other half may contain
  828. X     * too many values (more than "topmaxvals" or "botmaxvals").
  829. X     */
  830. X    while (topsize > topmaxvals)
  831. X    {   onefreq = (--ct)->ct_freq;
  832. X        topsize--; topfreq -= onefreq;
  833. X        botsize++; botfreq += onefreq;
  834. X    }
  835. X    while (botsize > botmaxvals)
  836. X    {   onefreq = (ct++)->ct_freq;
  837. X        topsize++; topfreq += onefreq;
  838. X        botsize--; botfreq -= onefreq;
  839. X    }
  840. X
  841. X    /*
  842. X     * Second, the number of bits required to represent the values in
  843. X     * each half may violate PKZIP's requirement (implicit in the way
  844. X     * trees are compressed in an imploded file) that no code string in
  845. X     * the top half may be longer than any code string in the bottom
  846. X     * half.
  847. X     */
  848. X    localminbits = preflen + 1;
  849. X    if (localminbits < minbits) localminbits = minbits;
  850. X    for (;;)
  851. X    {   for (maxshort = preflen + 1, n = 1;
  852. X             n < botsize;
  853. X             maxshort++, n <<= 1) ;
  854. X        if (n > botsize) maxshort--;
  855. X        if (maxshort < localminbits) maxshort = localminbits;
  856. X        if (maxshort > topmaxbits) maxshort = topmaxbits;
  857. X        for (minlong = preflen + 1, n = 1;
  858. X             n < topsize;
  859. X             minlong++, n <<= 1) ;
  860. X        if (minlong <= maxshort) break;
  861. X        onefreq = (--ct)->ct_freq;
  862. X        topsize--; topfreq -= onefreq;
  863. X        botsize++; botfreq += onefreq;
  864. X    }
  865. X
  866. X    /*
  867. X     * Third, the number of elements in the top half must be enough to
  868. X     * result in each string having at least "minbits" bits in all.
  869. X     */
  870. X    n = 1 << (minbits - preflen - 1);
  871. X    while (topsize < n)
  872. X    {   onefreq = (ct++)->ct_freq;
  873. X        topsize++; topfreq += onefreq;
  874. X        botsize--; botfreq -= onefreq;
  875. X    }
  876. X
  877. X    /*
  878. X     * Now that the sizes of the two halves of the partition have been
  879. X     * finalized, process the top and bottom halves via recursion.
  880. X     */
  881. X    retcode = ct_split (part, topsize, topfreq,
  882. X                        prefix | (1 << (15-preflen)),
  883. X                        preflen + 1, localminbits, maxshort);
  884. X    if (retcode != IM_OK) return retcode;
  885. X    ct = part + topsize;
  886. X    retcode = ct_split (ct, botsize, botfreq,
  887. X                        prefix, preflen + 1, (int)ct[-1].ct_len, maxbits);
  888. X    if (retcode != IM_OK) return retcode;
  889. X
  890. X    /* That's all. */
  891. X    return IM_OK;
  892. X
  893. X#ifdef VALIDATE
  894. badarg:
  895. X    fprintf (stderr, "\nError in ct_split: bad argument(s)");
  896. X    putchar ('\n'); fflush (stdout); fflush (stderr);
  897. X    /* abort (); */
  898. X    return IM_BADARG;
  899. X#endif /* VALIDATE */
  900. X
  901. oops:
  902. X#ifdef VALIDATE
  903. X    putchar ('\n'); fflush (stdout); fflush (stderr);
  904. X    /* abort (); */
  905. X#endif /* VALIDATE */
  906. X    return IM_LOGICERR;
  907. X}
  908. X
  909. X
  910. X/***********************************************************************
  911. X *
  912. X * Sorting function -- descending order by source value frequency.
  913. X *
  914. X * This sorting function is used at the start of the code tree con-
  915. X * struction process, before the bit string values are assigned.
  916. X * To ensure consistent behaviour on all machines, we use the source
  917. X * values as secondary sort key, but this is not mandatory.
  918. X */
  919. X
  920. local
  921. int
  922. ct_fsort (tr1, tr2)
  923. X    TRDATA *tr1, *tr2;
  924. X{   long d;
  925. X    int v;
  926. X
  927. X    d = (long) tr1->ct_freq - (long) tr2->ct_freq;
  928. X    if (d < 0) return 1;
  929. X    if (d > 0) return -1;
  930. X    v = (int) tr1->ct_val - (int) tr2->ct_val;
  931. X    if (v < 0) return 1;
  932. X    if (v > 0) return -1;
  933. X    return 0;
  934. X}
  935. X
  936. X
  937. X/***********************************************************************
  938. X *
  939. X * Sorting function -- ascending order by bit string length; if lengths
  940. X * are the same, ascending order by source value.
  941. X *
  942. X * This sorting function is used after the bit string values have been
  943. X * assigned.  
  944. X */
  945. X
  946. local
  947. int
  948. ct_rsort (cr1, cr2)
  949. X    RESORT *cr1, *cr2;
  950. X{   int d;
  951. X
  952. X    d = (int) cr1->ct_rlen - (int) cr2->ct_rlen;
  953. X    if (d > 0) return 1;
  954. X    if (d < 0) return -1;
  955. X    d = (int) cr1->ct_rval - (int) cr2->ct_rval;
  956. X    if (d > 0) return 1;
  957. X    if (d < 0) return -1;
  958. X    return 0;
  959. X}
  960. X
  961. X
  962. X/***********************************************************************
  963. X *
  964. X * Allocate the code trees.
  965. X */
  966. X
  967. ImpErr
  968. ct_init ()
  969. X{   ImpErr retcode;
  970. X    int i;
  971. X
  972. X#ifdef DEBUG
  973. X    if (256*sizeof(TRDATA) > MA_BUFSIZE*sizeof(MATCH)) return IM_LOGICERR;
  974. X#endif /* DEBUG */
  975. X
  976. X    retcode = ct_windup ();
  977. X        if (retcode != IM_OK) return retcode;
  978. X
  979. X    ct_litc_num = 0;
  980. X    ct_lit2_num = 0;
  981. X    ct_strg_num = 0;
  982. X
  983. X    for (i = 255; i >= 0;  i--)
  984. X        ct_litc_freq[i] = 0;
  985. X    for (i = 63; i >= 0; i--)
  986. X        ct_len2_freq[i] = 0, ct_len3_freq[i] = 0,
  987. X        ct_dst2_freq[i] = 0, ct_dst3_freq[i] = 0;
  988. X
  989. X    retcode = ct_alloc (256, &ct_litc_tree);
  990. X    if (retcode != IM_OK) return retcode;
  991. X    retcode = ct_alloc  (64, &ct_len2_tree);
  992. X    if (retcode != IM_OK) return retcode;
  993. X    retcode = ct_alloc  (64, &ct_len3_tree);
  994. X    if (retcode != IM_OK) return retcode;
  995. X    retcode = ct_alloc  (64, &ct_dst2_tree);
  996. X    if (retcode != IM_OK) return retcode;
  997. X    retcode = ct_alloc  (64, &ct_dst3_tree);
  998. X    if (retcode != IM_OK) return retcode;
  999. X
  1000. X    return IM_OK;
  1001. X}
  1002. X
  1003. X
  1004. X/***********************************************************************
  1005. X *
  1006. X * Tally a "string match" data set.  The tally results will be used to
  1007. X * determine how large the imploded result will be.
  1008. X */
  1009. X
  1010. ImpErr
  1011. ct_tally (ma)
  1012. X         MATCH *ma;             /* match data to write out */
  1013. X{   register int ch;
  1014. X    int dist = ma->ma_dist;
  1015. X
  1016. X    /* Tally up the latest data. */
  1017. X    if (dist == 0) {                 /* literal character */
  1018. X            ct_litc_num++;
  1019. X            ch = ma->l.ma_litc[0];
  1020. X                ct_litc_freq[ch]++;
  1021. X
  1022. X    } else if (dist < 0) {           /* 2-character match */
  1023. X            ct_lit2_num++;
  1024. X            ch = ma->l.ma_litc[0];
  1025. X                ct_litc_freq[ch]++;
  1026. X            ch = ma->l.ma_litc[1];
  1027. X                ct_litc_freq[ch]++;
  1028. X            ch = ((-dist-1) >> fd.fd_nbits) & 0x3f;
  1029. X                ct_dst2_freq[ch]++;
  1030. X            ct_len2_freq[0]++;
  1031. X
  1032. X     } else {                        /* 3-char or longer match */
  1033. X            ct_strg_num++;
  1034. X            ch = ((dist-1) >> fd.fd_nbits) & 0x3f;
  1035. X                ct_dst3_freq[ch]++;
  1036. X         /* We defer the update of ct_dst2_freq and ct_len2_freq until
  1037. X          * ct_mktrees:
  1038. X          *     ct_dst2_freq[ch]++;
  1039. X          * ch = ma->l.ma_length - 2;
  1040. X          *     if (ch > 63) ch = 63;
  1041. X          *     ct_len2_freq[ch]++;
  1042. X          */
  1043. X            ch = ma->l.ma_length - 3;
  1044. X                if (ch > 63) ch = 63;
  1045. X                ct_len3_freq[ch]++;
  1046. X    }
  1047. X
  1048. X    /* That's all. */
  1049. X    return IM_OK;
  1050. X}
  1051. X
  1052. X
  1053. X/***********************************************************************
  1054. X *
  1055. X * Construct all code trees, and then determine how big the imploded
  1056. X * file will be under both "literal tree" and "no literal tree" con-
  1057. X * ditions.  Choose the best option.
  1058. X */
  1059. X
  1060. ImpErr
  1061. ct_mktrees ()
  1062. X{   U_CHAR *c;
  1063. X    ImpErr retcode;
  1064. X    register long sum;
  1065. X    long len2, len3;
  1066. X    int n;
  1067. X
  1068. X    /* ct_tally did not update ct_dst2_freq and ct_len2_freq for matches of
  1069. X     * length > 2, so correct this now.
  1070. X     */
  1071. X    for (n = 62; n >= 0; n--) {
  1072. X        ct_dst2_freq[n] += ct_dst3_freq[n];
  1073. X        ct_len2_freq[n+1] += ct_len3_freq[n];
  1074. X    }
  1075. X    ct_dst2_freq[63] += ct_dst3_freq[63];
  1076. X    ct_len2_freq[63] += ct_len3_freq[63];
  1077. X
  1078. X    /*
  1079. X     * Construct the code trees and see how much space each will save.
  1080. X     *
  1081. X     * It is conceivable that a tree could result in a negative savings
  1082. X     * if its compressed form is sufficiently long.
  1083. X     *
  1084. X     * We need to construct the ZIP-file compressed representation of
  1085. X     * each tree in order to figure out how much space it will take.
  1086. X     * However, we don't save these tree representations now; rather,
  1087. X     * we'll wait until later and reconstruct the representations for
  1088. X     * whichever two (or three) trees we really need for the output.
  1089. X     */
  1090. X#ifdef IMPDEBUG
  1091. X    treename = (char *)NULL;
  1092. X#endif /* IMPDEBUG */
  1093. X
  1094. X    /* literal code tree */
  1095. X    retcode = ct_loadf    (ct_litc_tree,  ct_litc_freq);
  1096. X        if (retcode != IM_OK) return retcode;
  1097. X    retcode = ct_gencodes (ct_litc_tree, 1, 16, &ct_litc_saved);
  1098. X        if (retcode != IM_OK) return retcode;
  1099. X    retcode = ct_ziprep   (ct_litc_tree, &c);
  1100. X        if (retcode != IM_OK) return retcode;
  1101. X    ct_litc_saved -= (int) (c[0]+2) * 8;
  1102. X
  1103. X    /* length code tree (2) */
  1104. X    retcode = ct_loadf    (ct_len2_tree,  ct_len2_freq);
  1105. X        if (retcode != IM_OK) return retcode;
  1106. X    retcode = ct_gencodes (ct_len2_tree, 1, 16, &ct_len2_saved);
  1107. X        if (retcode != IM_OK) return retcode;
  1108. X    retcode = ct_ziprep   (ct_len2_tree, &c);
  1109. X        if (retcode != IM_OK) return retcode;
  1110. X    ct_len2_saved -= (int) (c[0]+2) * 8;
  1111. X
  1112. X    /* length code tree (3) */
  1113. X    retcode = ct_loadf    (ct_len3_tree,  ct_len3_freq);
  1114. X        if (retcode != IM_OK) return retcode;
  1115. X    retcode = ct_gencodes (ct_len3_tree, 1, 16, &ct_len3_saved);
  1116. X        if (retcode != IM_OK) return retcode;
  1117. X    retcode = ct_ziprep   (ct_len3_tree, &c);
  1118. X        if (retcode != IM_OK) return retcode;
  1119. X    ct_len3_saved -= (int) (c[0]+2) * 8;
  1120. X
  1121. X    /* distance code tree (2) */
  1122. X    retcode = ct_loadf    (ct_dst2_tree,  ct_dst2_freq);
  1123. X        if (retcode != IM_OK) return retcode;
  1124. X    retcode = ct_gencodes (ct_dst2_tree, 1,  8, &ct_dst2_saved);
  1125. X        if (retcode != IM_OK) return retcode;
  1126. X    retcode = ct_ziprep   (ct_dst2_tree, &c);
  1127. X        if (retcode != IM_OK) return retcode;
  1128. X    ct_dst2_saved -= (int) (c[0]+2) * 8;
  1129. X
  1130. X    /* distance code tree (3) */
  1131. X    retcode = ct_loadf    (ct_dst3_tree,  ct_dst3_freq);
  1132. X        if (retcode != IM_OK) return retcode;
  1133. X    retcode = ct_gencodes (ct_dst3_tree, 1,  8, &ct_dst3_saved);
  1134. X        if (retcode != IM_OK) return retcode;
  1135. X    retcode = ct_ziprep   (ct_dst3_tree, &c);
  1136. X        if (retcode != IM_OK) return retcode;
  1137. X    ct_dst3_saved -= (int) (c[0]+2) * 8;
  1138. X
  1139. X    /*
  1140. X     * Determine how big the compressed file will be
  1141. X     * with, and without, a literal character tree.
  1142. X     */
  1143. X
  1144. X    /* compressed length (no literal tree) */
  1145. X    sum  = ct_litc_num + ct_lit2_num + ct_strg_num;    /* initial bit */
  1146. X    sum += ct_litc_num * 8;                          /* literal bytes */
  1147. X    sum += (ct_lit2_num+ct_strg_num) * 6 - ct_len2_saved;  /* lengths */
  1148. X    sum += 8 * ct_len2_freq[63];                  /* oversize lengths */
  1149. X    sum += (ct_lit2_num+ct_strg_num) * (fd.fd_nbits+6)
  1150. X            - ct_dst2_saved;                             /* distances */
  1151. X    len2 = (sum+7) / 8;                           /* convert to bytes */
  1152. X
  1153. X    /* compressed length (with literal tree) */
  1154. X    sum  = ct_litc_num + 2*ct_lit2_num + ct_strg_num;  /* initial bit */
  1155. X    sum += (ct_litc_num+2*ct_lit2_num)*8 - ct_litc_saved;/* lit bytes */
  1156. X    sum += ct_strg_num * 6 - ct_len3_saved;                /* lengths */
  1157. X    sum += 8 * ct_len3_freq[63];                  /* oversize lengths */
  1158. X    sum += ct_strg_num * (fd.fd_nbits+6) - ct_dst3_saved;   /* dist's */
  1159. X    len3 = (sum+7) / 8;                           /* convert to bytes */
  1160. X
  1161. X    /*
  1162. X     * PKUNZIP 1.10 requires that the source value 255 in a "literal"
  1163. X     * tree must be represented by a bit string of length >= 10.  The
  1164. X     * literal tree was already adjusted to ensure that the value 255
  1165. X     * was given a bit string of length 10 or greater if possible.  If
  1166. X     * this did not succeed -- which would only happen if the longest
  1167. X     * bit string in the literal tree were of length 8 or 9 -- then the
  1168. X     * literal tree cannot be used.  In such a case, not much would be
  1169. X     * gained by using it anyway, so there's little reason to be upset.
  1170. X     */
  1171. X    if (ct_table[ct_litc_tree].ct_array[255].ct_len < 10)
  1172. X        len3 = len2;
  1173. X
  1174. X    /*
  1175. X     * Choose the method of compression which will use the least space
  1176. X     * for this particular file.  The possibilities are:  use a literal
  1177. X     * character tree; or, don't use a literal character tree.
  1178. X     */
  1179. X    if (len2 <= len3)
  1180. X    {   fd.fd_method = NO_LITERAL_TREE;
  1181. X        fd.fd_clen   = len2;
  1182. X        lit_tree     = -1;
  1183. X        len_tree     = ct_len2_tree;
  1184. X        dst_tree     = ct_dst2_tree;
  1185. X        retcode = ct_free (ct_litc_tree);
  1186. X            if (retcode != IM_OK) return retcode;
  1187. X        retcode = ct_free (ct_dst3_tree);
  1188. X            if (retcode != IM_OK) return retcode;
  1189. X        retcode = ct_free (ct_len3_tree);
  1190. X            if (retcode != IM_OK) return retcode;
  1191. X    }
  1192. X    else
  1193. X    {   fd.fd_method = LITERAL_TREE;
  1194. X        fd.fd_clen   = len3;
  1195. X        lit_tree     = ct_litc_tree;
  1196. X        len_tree     = ct_len3_tree;
  1197. X        dst_tree     = ct_dst3_tree;
  1198. X        retcode = ct_free (ct_dst2_tree);
  1199. X            if (retcode != IM_OK) return retcode;
  1200. X        retcode = ct_free (ct_len2_tree);
  1201. X            if (retcode != IM_OK) return retcode;
  1202. X    }
  1203. X
  1204. X    /* That's all. */
  1205. X    return IM_OK;
  1206. X}
  1207. X
  1208. X
  1209. X/***********************************************************************
  1210. X *
  1211. X * Output the code trees.
  1212. X */
  1213. X
  1214. ImpErr
  1215. ct_wrtrees (outfp)
  1216. X    FILE *outfp;                        /* output file */
  1217. X{   ImpErr retcode;
  1218. X    U_CHAR *c;
  1219. X
  1220. X    /* Output the literal tree, if any. */
  1221. X#ifdef IMPDEBUG
  1222. X    treename = "Literal";
  1223. X#endif /* IMPDEBUG */
  1224. X    if (lit_tree >= 0)
  1225. X    {   retcode = ct_ziprep (lit_tree, &c);
  1226. X            if (retcode != IM_OK) return retcode;
  1227. X        if (zfwrite ((char *) c, (int) (c[0]+2), 1, outfp) != 1)
  1228. X            return IM_IOERR;
  1229. X    }
  1230. X
  1231. X    /* Output the length tree. */
  1232. X#ifdef IMPDEBUG
  1233. X    treename = "Length";
  1234. X#endif /* IMPDEBUG */
  1235. X    retcode = ct_ziprep (len_tree, &c);
  1236. X        if (retcode != IM_OK) return retcode;
  1237. X    if (zfwrite ((char *) c, (int) (c[0]+2), 1, outfp) != 1)
  1238. X        return IM_IOERR;
  1239. X
  1240. X    /* Output the distance tree. */
  1241. X#ifdef IMPDEBUG
  1242. X    treename = "Distance";
  1243. X#endif /* IMPDEBUG */
  1244. X    retcode = ct_ziprep (dst_tree, &c);
  1245. X        if (retcode != IM_OK) return retcode;
  1246. X    if (zfwrite ((char *) c, (int) (c[0]+2), 1, outfp) != 1)
  1247. X        return IM_IOERR;
  1248. X
  1249. X    return IM_OK;
  1250. X}
  1251. X
  1252. X/* Macros for outputting bit string. */
  1253. X
  1254. X#define OUTBITS(value,length) \
  1255. X        {   retcode = bi_rlout ((int) (value), (int) (length)); \
  1256. X                if (retcode != IM_OK) return retcode; \
  1257. X        }
  1258. X#define OUTCODE(value,tree) \
  1259. X        {   ct_lookup (tree, value, bitstring, bitlength); \
  1260. X            retcode = bi_rlout (bitstring, bitlength); \
  1261. X                if (retcode != IM_OK) return retcode; \
  1262. X        }
  1263. X
  1264. X/***********************************************************************
  1265. X *
  1266. X * Output the body of the file in imploded form.
  1267. X */
  1268. ImpErr
  1269. ct_wrdata (outfp)
  1270. X         FILE *outfp;                   /* output (ZIP) file */
  1271. X{   MATCH *ma;
  1272. X    ImpErr retcode;
  1273. X    register int minmatch;
  1274. X    int bitstring, bitlength;
  1275. X    int bitmask = (1 << (fd.fd_nbits+1))-1;
  1276. X    /* Used to select the bottom 6 or 7 bits of a distance, which are
  1277. X     * output literally, plus 1 bit marking a distance
  1278. X     */
  1279. X    int matches;
  1280. X#ifdef  IMPDEBUG
  1281. X    long srcpos;
  1282. X#endif  /* IMPDEBUG */
  1283. X
  1284. X    /* Determine the minimum match length. */
  1285. X    minmatch = (lit_tree >= 0) ? 3 : 2;
  1286. X
  1287. X    /* Prepare the I/O. */
  1288. X    if (tflush (fd.fd_temp) != 0) return IM_IOERR;
  1289. X    trewind (fd.fd_temp);
  1290. X    retcode = bi_init (outfp);
  1291. X        if (retcode != IM_OK) return retcode;
  1292. X
  1293. X#ifdef  IMPDEBUG
  1294. X        srcpos = 0;
  1295. X        fprintf (stderr, "\nImploded output:\n");
  1296. X#endif  /* IMPDEBUG */
  1297. X
  1298. X    /* Read and process data from the temporary file. */
  1299. X    while ((matches =
  1300. X       tread ((char *) ma_buf, sizeof(MATCH), MA_BUFSIZE, fd.fd_temp)) > 0)
  1301. X       for (ma = ma_buf; matches > 0; ma++, matches--)
  1302. X    {
  1303. X        int dist = ma->ma_dist;
  1304. X        int len = 0;
  1305. X
  1306. X#ifdef  IMPDEBUG
  1307. X        fprintf (stderr, "%8ld: ", srcpos);
  1308. X#endif  /* IMPDEBUG */
  1309. X
  1310. X        if (dist < 0) {
  1311. X            dist = -dist, len = 2;
  1312. X        } else if (dist > 0) {
  1313. X            len = ma->l.ma_length;
  1314. X        }
  1315. X
  1316. X        /* Output distance and length if enough characters match. */
  1317. X        if (len >= minmatch)
  1318. X        {   /* "matched string" header bit (0) */
  1319. X#ifdef  IMPDEBUG
  1320. X            fprintf (stderr, "str (dst=%d,len=%d)  ",
  1321. X                     dist, len);
  1322. X            srcpos += len;
  1323. X#endif  /* IMPDEBUG */
  1324. X
  1325. X            /* ouput one zero bit then the distance */
  1326. X            dist--;
  1327. X            OUTBITS ((dist << 1) & bitmask, fd.fd_nbits + 1);
  1328. X            OUTCODE (dist >> fd.fd_nbits, dst_tree);
  1329. X
  1330. X            /* length -- depends on how it compares to maximum */
  1331. X            len -= minmatch;
  1332. X            if (len >= 63)
  1333. X            {   /* big length -- output code for 63, then surplus */
  1334. X                OUTCODE (63, len_tree);
  1335. X                OUTBITS ((len - 63), 8);
  1336. X            }
  1337. X            else
  1338. X            {   /* small length -- output code */
  1339. X                OUTCODE (len, len_tree);
  1340. X        }   }
  1341. X        else if (lit_tree >= 0)
  1342. X        {   /* first or single literal -- header bit (1) plus char */
  1343. X#ifdef  IMPDEBUG
  1344. X            fprintf (stderr, "lit (val=%02x)  ",
  1345. X                     ma->l.ma_litc[0] & 0xff);
  1346. X            srcpos++;
  1347. X#endif  /* IMPDEBUG */
  1348. X            OUTBITS (1, 1);
  1349. X            OUTCODE (ma->l.ma_litc[0], lit_tree);
  1350. X            if (len == 2)
  1351. X            {   /* second literal -- header bit (1) plus char */
  1352. X#ifdef  IMPDEBUG
  1353. X                fprintf (stderr, "\n%8ld: lit (val=%02x)  ",
  1354. X                         srcpos, ma->l.ma_litc[1] & 0xff);
  1355. X                srcpos++;
  1356. X#endif  /* IMPDEBUG */
  1357. X                OUTBITS (1, 1);
  1358. X                OUTCODE (ma->l.ma_litc[1], lit_tree);
  1359. X        }   }
  1360. X        else
  1361. X        {   /* single literal -- header bit (1) plus char */
  1362. X#ifdef  IMPDEBUG
  1363. X            fprintf (stderr, "lit (val=%02x)  ",
  1364. X                     ma->l.ma_litc[0] & 0xff);
  1365. X            srcpos++;
  1366. X#endif  /* IMPDEBUG */
  1367. X            OUTBITS ((ma->l.ma_litc[0] << 1) + 1, 9);
  1368. X        }
  1369. X#ifdef  IMPDEBUG
  1370. X        putc ('\n', stderr);
  1371. X#endif  /* IMPDEBUG */
  1372. X    }
  1373. X
  1374. X    /* Make sure we hit EOF on input without an error. */
  1375. X    if (terror (fd.fd_temp)
  1376. X#ifndef MINIX
  1377. X#ifndef __TURBOC__      /* TurboC 2.0 does not set the EOF flag (?) */
  1378. X        || !teof (fd.fd_temp)
  1379. X#endif /* !__TURBOC__ */
  1380. X#endif /* !MINIX */
  1381. X       )
  1382. X      return IM_IOERR;
  1383. X    retcode = bi_windup ();
  1384. X        if (retcode != IM_OK) return retcode;
  1385. X
  1386. X    /* That's all. */
  1387. X    return IM_OK;
  1388. X}
  1389. X
  1390. X#undef  OUTBITS
  1391. X#undef  OUTCODE
  1392. X
  1393. X
  1394. X/***********************************************************************
  1395. X *
  1396. X * Deallocate all code trees.
  1397. X */
  1398. X
  1399. ImpErr
  1400. ct_windup ()
  1401. X{   int n;
  1402. X    static windup_already_called = 0;
  1403. X    ImpErr retcode;
  1404. X
  1405. X    if (windup_already_called)
  1406. X    {   /* Discard any old code trees. */
  1407. X        for (n = 0; n < MAXTREES; n++)
  1408. X        {   if (ct_table[n].ct_array != NULL)
  1409. X            {   retcode = ct_free (n);
  1410. X                if (retcode != IM_OK) return retcode;
  1411. X    }   }   }
  1412. X    else
  1413. X    {   /* Initialize the list of active code trees. */
  1414. X        for (n = 0; n < MAXTREES; n++)
  1415. X        {   ct_table[n].ct_array = NULL;
  1416. X            ct_table[n].ct_size  = 0;
  1417. X        }
  1418. X        windup_already_called = 1;
  1419. X    }
  1420. X
  1421. X    /* That's all. */
  1422. X    return IM_OK;
  1423. X}
  1424. X
  1425. X
  1426. X/**********************************************************************/
  1427. END_OF_FILE
  1428. if test 45523 -ne `wc -c <'im_ctree.c'`; then
  1429.     echo shar: \"'im_ctree.c'\" unpacked with wrong size!
  1430. fi
  1431. # end of 'im_ctree.c'
  1432. fi
  1433. echo shar: End of archive 7 \(of 7\).
  1434. cp /dev/null ark7isdone
  1435. MISSING=""
  1436. for I in 1 2 3 4 5 6 7 ; do
  1437.     if test ! -f ark${I}isdone ; then
  1438.     MISSING="${MISSING} ${I}"
  1439.     fi
  1440. done
  1441. if test "${MISSING}" = "" ; then
  1442.     echo You have unpacked all 7 archives.
  1443.     rm -f ark[1-9]isdone
  1444. else
  1445.     echo You still need to unpack the following archives:
  1446.     echo "        " ${MISSING}
  1447. fi
  1448. ##  End of shell archive.
  1449. exit 0
  1450.